<template>
  <div class="banneradd_content">
    <div class="form_content">
      <h3 style="margin-top: 0 !important;">基本信息</h3>
      <el-form ref="bannerForm" :disabled="routeType === 'detail'" :rules="bannerFormRules" :model="bannerForm"
        label-width="100px" class="demo-ruleForm">
        <el-row :gutter="24" type="flex">
          <el-col :span="10">
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="bannerForm.name" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="是否显示" prop="showStatus">
              <el-radio-group v-model="bannerForm.showStatus" size="small">
                <el-radio label="0">显示</el-radio>
                <el-radio label="1">不显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="10">
            <el-form-item label="图片" prop="imgUrl">
              <el-upload v-if="!bannerForm.imgUrl" name="multipartFile" :limit="1" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload" list-type="picture-card" :action="action" :data="upData"
                :headers="headers" :on-error="fileUploadError" class="imgUpload"><i size="12"
                  class="el-icon-plus" /><br><span class="txt">上传</span></el-upload>
              <template v-if="bannerForm.imgUrl">
                <div style="display: flex;">
                  <img v-if="bannerForm.imgUrl" :src="bannerForm.imgUrl" style="width: 120px;" alt="">
                  <div v-if="routeType !== 'detail'" style="
                      width: 120px;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      border-radius: 5px;
                      border: 1px dashed #ccc;
                      text-align: center;
                      color: #ccc;
                      margin-left: 5px;
                    ">
                    <i style="cursor: pointer" class="el-icon-delete" @click="delImg" />
                  </div>
                </div>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="描述" prop="describes">
              <el-input v-model.trim="bannerForm.describes" :rows="4" maxlength="200" show-word-limit type="textarea"
                style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="10">
            <el-form-item label="链接地址" prop="linkUrl">
              <el-input v-model.trim="bannerForm.linkUrl" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="bannerForm.sort" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="10">
            <el-form-item label="平台" prop="type">
              <el-select v-model="bannerForm.type" placeholder="请选择..." clearable >
                <el-option label="小程序轮播图" value="0"></el-option>
                <el-option label="收银机轮播图" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div style="display: flex;justify-content: end;">
      <el-button v-if="routeType === 'add' || routeType === ''" style="width: 88px" class="submitBtn"
        @click.stop="addBtn">确定</el-button>
      <el-button v-if="routeType === 'edit'" class="submitBtn" style="width: 88px"
        @click.stop="updateGoodsDetail">提交</el-button>
      <el-button v-if="routeType !== 'detail'" class="celBtn" style="width: 88px" @click.stop="cancelbtn">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addBanner, getBannerById, updateBanner } from '@/api/h5'
export default {
  name: 'BannerAdd',
  data() {
    return {
      headers: { token: getToken() },
      action: process.env.VUE_APP_UPLOAD_BASE_API + '/file/uploadFile',
      upData: {
        fileType: '0'
      },
      routeType: 'add',
      id: '',
      bannerForm: {
        name: '',
        imgUrl: '',
        linkUrl: '',
        sort: null, // 排序数字
        showStatus: '0', // 是否显示 0显示
        describes: '', // 描述
        type: '' // 0小程序轮播图 1收银机轮播图
      },
      bannerFormRules: {
        name: [
          {
            required: true,
            message: '请输入轮播图名称',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 15,
            message: '轮播图名称不能超过15个字符',
            trigger: 'blur'
          },
          {
            pattern: /^([\u4e00-\u9fa5])+$/,
            message: '只能输入中文',
            trigger: 'blur'
          }
        ],
        imgUrl: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'blur'
          }
        ],
        linkUrl: [
          {
            min: 0,
            max: 20,
            message: '链接地址长度不能超过20个字符',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            min: 0,
            max: 2,
            message: '排序应为1-2位数字',
            trigger: 'blur'
          },
          {
            pattern: /^\+?[0-9]\d*$/,
            message: '只能输入数字',
            trigger: 'blur'
          }
        ],
        showStatus: [
          {
            required: true,
            message: '请选择是否显示',
            trigger: 'blur'
          }
        ],
        describes: [
          {
            min: 0,
            max: 200,
            message: '最多输入200个字',
            trigger: 'blur'
          }
        ],
        type:[
          {
            required: true,
            message: '请选择所属平台',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.routeType = this.$route.query.routeType
      ? this.$route.query.routeType
      : 'add'
    this.id = this.$route.query?.id
    if (this.id) {
      this.getBannerById()
    }
    console.log(this.id, 'id')
  },
  methods: {
    async getBannerById() {
      const res = await getBannerById({ id: this.id })
      if (res.code === 200) {
        this.bannerForm = res.data
        this.$set(this.bannerForm, 'sort', String(res.data.sort ? res.data.sort : ''))
      } else {
        // this.$message.error('获取数据失败')
      }
    },
    addBtn() {
      this.$refs.bannerForm.validate(async (isOk) => {
        if (isOk) {
          const res = await addBanner(this.bannerForm)
          console.log(res.code)
          if (res.code === 200) {
            this.$message.success('添加成功')
            this.$refs.bannerForm.resetFields()
            this.closeTag('swiperInfo')
          } else {
            // this.$message.error(res.message)
          }
        } else {
          this.$message.warning('请检查填写的信息')
        }
      })
    },
    cancelbtn() {
      // this.$refs.bannerForm.resetFields()
      this.closeTag('swiperInfo')
    },
    handleAvatarSuccess(res, file) {
      this.bannerForm.imgUrl =
        this.$store.getters.imgBaseUrl +
        res.data.filePath +
        res.data.fileNewName
      console.log(this.$store.getters.imgBaseUrl, '基地址')
      console.log(res)
      this.$message.success('上传成功')
      console.log(this.bannerForm.imgUrl)
    },
    beforeAvatarUpload(file) {
      // console.log('before', file)
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      const isOKType =
        fileType === '.jpg' || fileType === '.png' || fileType === '.jpeg'
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg')
      }

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isLt2M && isOKType
    },
    delImg() {
      this.bannerForm.imgUrl = ''
    },
    fileUploadError(res) {
      this.$message.error(res.message)
    },
    async updateGoodsDetail() {
      this.$refs.bannerForm.validate(async (isOk) => {
        if (isOk) {
          const res = await updateBanner(this.bannerForm)
          console.log(res.code)
          if (res.code === 200) {
            this.$message.success('修改成功')
            this.$refs.bannerForm.resetFields()
            this.$router.push('swiperInfo')
          } else {
            // this.$message.error(res.message)
          }
        } else {
          this.$message.warning('请检查填写的信息')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.banneradd_content {
  height: 100%;
  padding: 32px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  /* background-color: #fff; */
  .form_content {
    // padding: 20px;
    // padding-top: 50px;
    flex: 1;
    background-color: #fff;

    .imgUpload {
      ::v-deep .el-upload:hover {
        border-color: #409eff;
      }

      ::v-deep .el-upload {
        position: relative;
        margin-bottom: 10px;
        margin-left: 5px;
        width: 120px;
        height: 128px;
        line-height: 30px;
        padding-top: 35px;
      }

      .txt {
        color: #595858;
        font-size: 12px;
      }
    }
  }
}

.el-upload--picture-card i {
  font-size: 12px !important;
}

.el-button--small {
  padding: 9px 0;
}

::deep el-button {
  text-align: center;
}

.el-row {
  margin-bottom: 30px;

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
